﻿using System;
using System.Windows.Forms;

namespace Moe.ECamel.Client.WinForms.Common
{
	public class ECamelDateTimeBox : DateTimePicker
	{
		public void Bind(object dataSource, string dataMember)
		{
			var binding = new Binding("Value", dataSource, dataMember, true);
			this.DataBindings.Add(binding);
			binding.Format += Binding_Format;
			binding.Parse += Binding_Parse;
		}

		/// <summary>
		/// Occurs when the property of a control is bound to a data value.
		/// </summary>
		private void Binding_Format(object sender, ConvertEventArgs e)
		{
			// If the value to display is null:
			if (e.Value == null)
			{
				// Turn off 'Has Value' indicator:
				this.Checked = false;
				// We cannot set null, and we don't want to trigger a value change event, so we set a stub value:
				e.Value = this.Value;
			}
			else
			{
				// Turn on 'Has Value' indicator:
				this.Checked = true;
			}
		}

		/// <summary>
		/// Occurs when the value of a data-bound control changes.
		/// </summary>
		private void Binding_Parse(object sender, ConvertEventArgs e)
		{
			// If the user set a value:
			if (this.Checked)
				e.Value = Convert.ToDateTime(e.Value);
			else
				e.Value = new Nullable<DateTime>();
		}
	}
}
